import random
import pygame
import math

# 1.初始化界面
pygame.init()
# 设置窗口的大小
screen = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption('飞机大战')
# 加载图标图片
icon = pygame.image.load('ufo.png')
# 设置窗口图标
pygame.display.set_icon(icon)
# 加载背景图片
BackImage = pygame.image.load('bg.png')

# 添加音乐
pygame.mixer.music.load('bg.wav')
pygame.mixer.music.play(-1)  # 单曲循环
# 添加射中音效
bao_sound = pygame.mixer.Sound('exp.wav')

# 射击分数
score = 0
font = pygame.font.Font('freesansbold.ttf', 32)


def show_score():
    text = f"Score:{score}"
    score_render = font.render(text, True, (0, 255, 0))
    screen.blit(score_render, (10, 10))


# 游戏结束
isOver = False
Over_font = pygame.font.Font('freesansbold.ttf', 64)


def check_isOver():
    if isOver:
        text = "Game Over"
        render = Over_font.render(text, True, (255, 0, 0))
        screen.blit(render, (200, 300))


# 飞机
playerImg = pygame.image.load('player.png')
playerX = 400
playerY = 500
playerStep = 0  # 玩家移动速度


def move_player():
    global playerX
    # 防止飞机出界  因为飞机的大小为64 * 64
    playerX += playerStep
    if playerX > 736:
        playerX = 736
    if playerX < 0:
        playerX = 0


# 敌人
number_of_enemies = 6  # 敌人数量


class Enemy:
    def __init__(self):
        try:
            self.img = pygame.image.load('enemy.png')
        except pygame.error as e:
            print(f"敌人图片加载失败: {e}")
        self.x = random.randint(200, 600)
        self.y = random.randint(50, 250)
        self.step = random.randint(2, 6)  # 敌人移动速度

    def reset(self):
        self.x = random.randint(200, 600)
        self.y = random.randint(50, 250)


enemies = []
for i in range(number_of_enemies):
    enemies.append(Enemy())


def distance(bx, by, ex, ey):
    a = bx - ex
    b = by - ey
    return math.sqrt(a * a + b * b)  # 开根号


# 子弹
class Bullet:
    def __init__(self):
        try:
            self.img = pygame.image.load('bullet.png')
        except pygame.error as e:
            print(f"子弹图片加载失败: {e}")
        self.x = playerX + 16
        self.y = playerY + 10
        self.step = 10  # 子弹移动速度

    def hit(self):
        global score
        for e in enemies:
            if distance(self.x, self.y, e.x, e.y) < 30:
                bao_sound.play()
                e.reset()
                score += 1
                return True
        return False


bullets = []  # 保存现有的子弹  超过边界则去除


def show_bullet():
    global bullets
    new_bullets = []
    for b in bullets:
        screen.blit(b.img, (b.x, b.y))
        if b.hit():
            continue
        b.y -= b.step  # 子弹往上移动
        if b.y >= 0:
            new_bullets.append(b)
    bullets = new_bullets


# 显示敌人，并且实现敌人的移动和下层
def show_enemy():
    global isOver
    for e in enemies:
        screen.blit(e.img, (e.x, e.y))
        e.x += e.step
        if e.x > 736 or e.x < 0:
            e.step = -e.step  # 改变移动方向
            e.y += 40  # 向下移动一定距离
            if e.y > 450:
                isOver = True
                print("Game Over")
                enemies.clear()


# 创建一个Clock对象来控制帧率
clock = pygame.time.Clock()
# 设置帧率
FPS = 60

# 2.游戏主循环
running = True
while running:
    # 限制帧率
    clock.tick(FPS)
    screen.blit(BackImage, (0, 0))  # 在游戏主循环中，每次循环都将这个背景图像绘制到屏幕的左上角，最后更新显示
    show_score()

    for event in pygame.event.get():  # 遍历所有的事件队列，获取当前发生的所有事件。
        if event.type == pygame.QUIT:  # 检查当前事件是否为关闭窗口事件（即用户点击了窗口的关闭按钮），如果是，则将 running 设置为 False，从而使主循环停止
            running = False
        if event.type == pygame.KEYDOWN:  # 如果是键盘按下.a向左移 d向右移
            if event.key == pygame.K_d:
                playerStep = 5
            elif event.key == pygame.K_a:
                playerStep = -5
            elif event.key == pygame.K_SPACE:
                bullets.append(Bullet())
        if event.type == pygame.KEYUP:  # 松开停止
            playerStep = 0

    screen.blit(playerImg, (playerX, playerY))  # 飞机的初始化位置
    move_player()
    show_enemy()
    show_bullet()
    check_isOver()
    # 更新显示
    pygame.display.update()

pygame.quit()